<?php
set_time_limit(600);
require_once('config.php');
require_once("lib/Comm.class.php");
require_once('lib/Db.class.php');
require_once('lib/Queue.class.php');
//require_once('lib/Crawler.class.php');

class Worker
{
    public function collectUsedRecord()
    {
        $count = -1;
        $obj = Comm::connDb();
        $sql = "DELETE FROM queue WHERE status=1;"; // 清理执行过的任务
        $obj->exec($sql);
        $sql = "SELECT COUNT(*) FROM dorm_code;";
        $result = $obj->query($sql);
        if(isset($result[0])) $count = $result[0][0];
        $page = 0;
        $pageSize = 100;
        $sum = 0;
        while($page <= (int)($count / $pageSize))
        {
            $offset = $page * $pageSize;
            $sql = "SELECT dorm FROM dorm_code LIMIT $offset, $pageSize;";
            $result = $obj->query($sql);
            //if($page == (int)($count / $pageSize)) var_dump($result);
            // do some thing
            $cnt = count($result);
            $sum += $cnt;
            //echo "sum = $sum, this page = $cnt\n";
            $q = new Queue();
            $end = date('Y-m-d');
            $param = array();
            $task = array();
            for($i = 0; $i < $cnt; $i++)
            {
                $sql = "SELECT MAX(time) as time FROM used WHERE dorm='".$result[$i]['dorm']."';";
                $info = $obj->query($sql);
                if(isset($info[0]) && !empty($info[0]['time'])) 
                    $start = date('Y-m-d', strtotime($info[0]['time']." +1 days"));
                else $start = '2017-01-01';
                
                //echo "dorm: ".$param['dorm']." start: ".$param['start']." end: ".$param['end']."\n";
                $t['dorm'] = $result[$i]['dorm'];
                $t_start = $start;
                while(Comm::dateCount($t_start, $end) >= 0)
                {
                    $t_end = date('Y-m-d', strtotime($t_start." +9 days"));
                    $d = Comm::dateCount($t_end, $end);
                    if($d < 0) { $t_end = $end; $d = 0; }
                    /* -------------------------------------------------------- */
                    $t['start'] = $t_start;
                    $t['end'] = $t_end;
                    $t['type'] = 'used';
                    array_push($param, $t);
                    $t['start'] = date('Y-m-d', strtotime($t_start." -1 days")); // 多查询前一天
                    $t['type'] = 'buy';
                    array_push($param, $t);
                    array_push($task, dirname(__FILE__).'/task/CrawlRecord.php');
                    array_push($task, dirname(__FILE__).'/task/CrawlRecord.php');
                    /* -------------------------------------------------------- */
                    $t_start = date('Y-m-d', strtotime($t_end." +1 days"));
                }
            }
            // 将任务加入队列
            if(!empty($task)) $q->addTask($task, $param);
            $page++;
        }
    }

    public function checkTask($total = 1, $i = 0)
    {
        $phpcmd = PHPCMD.'/php';
        $q = new Queue();
        $result = $q->getTask($total, $i, 100);
        //var_dump($result);
        if(empty($result)) 
        { 
            echo date('Y-m-d H:i:s')."  no task!\n"; 
            $q->cleanTask();
            return; 
        }
        foreach($result as $t)
        {
            $job = $phpcmd . " " . escapeshellarg($t['task']) . " ". 
                    escapeshellarg(Comm::a2s($t['param']))." >> ".dirname(__FILE__)."/worker_".date('Y-m-d').".log 2>&1";
            echo date('Y-m-d H:i:s')."  ".$t['task']." ".Comm::a2s($t['param'])."\n";
            exec($job);
            $q->updateTask($t['id']);
        }   
    }
}

$worker = new Worker();
if(isset($argv[1]) && ($argv[1] == 'collect'))
{
    echo "Run collectUsedRecord on ".date("Y-m-d H:i:s")."\n";
    $worker->collectUsedRecord();
}
else if(isset($argv[1]) && ($argv[1] == 'check'))
{
    $total = 1; $i = 0;
    if(isset($argv[2])) $total = $argv[2];  // 总进程数
    if(isset($argv[3])) $i =  $argv[3];     // 当前进程
    $worker->checkTask($total, $i);
}
else
{
    //$worker->collectUsedRecord();
    $worker->checkTask();
}
exit;
?>
